#!/bin/sh -e

case "$1" in
    configure)
	if ! id tigase > /dev/null 2>&1 ; then
	    adduser --system --home /usr/share/tigase --no-create-home \
		--ingroup nogroup --disabled-password --shell /bin/false \
		tigase
	fi
	chown tigase:adm /var/log/tigase
	chown tigase:root /etc/tigase /etc/tigase/certs \
		/etc/tigase/certs/rsa-keystore /etc/tigase/certs/truststore \
		/var/spool/tigase
	chmod 750 /var/log/tigase /var/spool/tigase \
		/etc/tigase /etc/tigase/certs
	sed -i 's/$HOST_NAME/'`hostname --fqdn`'/g' /etc/tigase/init.properties*

	if grep -q 'db=derby$' /etc/tigase/init.properties
		DERBYDB=`sed -n 's/.*user-db-uri.*jdbc:derby://;s/;.*//p' /etc/tigase/init.properties`
	then
		if [ -n "$DERBYDB" ] && [ ! -d "$DERBYDB" ] && [ -r /usr/lib/jvm/java-6-sun/db/lib/derby.jar ]
		then
			echo "Creating Derby database for Tigase in \`$DERBYDB' ..."
			OLDCWD=`pwd`
			cd /usr/share/tigase
			scripts/derby-db-create.sh "$DERBYDB" >/dev/null
			[ -e derby.log ] && rm *.log
			chown -R tigase "$DERBYDB"
			cd $OLDCWD
		fi
	fi
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
	echo "$0 called with unknown argument \`$1'" >&2
	exit 1
    ;;
esac

#DEBHELPER#
